<template>
  <div class="app-container">
    <!-- 桌面端布局 -->
    <div v-if="!isMobile">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item
          label="岗位编码"
          prop="code"
        >
          <el-input
            v-model="queryParams.code"
            placeholder="请输入岗位编码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item
          label="岗位名称"
          prop="name"
        >
          <el-input
            v-model="queryParams.name"
            placeholder="请输入岗位名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item
          label="状态"
          prop="status"
        >
          <el-select
            v-model="queryParams.status"
            placeholder="岗位状态"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >搜索</el-button>
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
          >重置</el-button>
        </el-form-item>
      </el-form>

      <el-row
        :gutter="10"
        class="mb8"
      >
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['permission:post:post']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['permission:post:{id}:put']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['permission:post:{id}:delete']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['permission:post:export:get']"
          >导出</el-button>
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="postList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column
          label="岗位编号"
          align="center"
          prop="id"
        />
        <el-table-column
          label="岗位编码"
          align="center"
          prop="code"
        />
        <el-table-column
          label="岗位名称"
          align="center"
          prop="name"
        />
        <el-table-column
          label="岗位排序"
          align="center"
          prop="sort"
        />
        <el-table-column
          label="状态"
          align="center"
          prop="status"
          :formatter="statusFormat"
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="create_datetime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.create_datetime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          v-if="
            hasPermi(['permission:post:{id}:put', 'permission:post:{id}:delete'])
          "
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['permission:post:{id}:put']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['permission:post:{id}:delete']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.page_size"
        @pagination="getList"
      />
    </div>

    <!-- 移动端布局 -->
    <div v-if="isMobile" class="mobile-container">
      <!-- 移动端搜索表单 -->
      <div class="mobile-search-form">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="mobile-form">
          <el-form-item label="岗位编码" prop="code">
            <el-input v-model="queryParams.code" placeholder="请输入岗位编码" clearable size="small" style="width: 100%"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="岗位名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入岗位名称" clearable size="small" style="width: 100%"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="岗位状态" clearable size="small" style="width: 100%">
              <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" :style="{
              backgroundColor: theme,
              borderColor: theme,
              width: '100%'
            }">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" style="width: 100%; margin-top: 10px;">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 移动端操作按钮 -->
      <div class="mobile-action-buttons">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd"
              v-hasPermi="['permission:post:post']" style="width: 100%">新增
            </el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate"
              v-hasPermi="['permission:post:{id}:put']" style="width: 100%">修改
            </el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" style="margin-top: 10px">
          <el-col :span="12">
            <el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['permission:post:{id}:delete']" style="width: 100%">删除
            </el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="warning" plain icon="el-icon-download" size="small" @click="handleExport"
              v-hasPermi="['permission:post:export:get']" style="width: 100%">导出
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 移动端卡片列表 -->
      <div class="mobile-card-list">
        <el-card 
          v-for="(item, index) in postList" 
          :key="index"
          class="mobile-card"
          shadow="hover">
          <div class="mobile-card-header">
            <div class="card-title">
              <span class="name">{{ item.name }}</span>
              <span class="code">({{ item.code }})</span>
            </div>
            <div v-if="item.status === 1" class="status-tag active">正常</div>
            <div v-else class="status-tag inactive">停用</div>
          </div>
          
          <!-- 岗位信息 -->
          <div class="mobile-card-info">
            <div class="info-item">
              <span class="info-label">岗位编号：</span>
              <span class="info-value">{{ item.id }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">排序：</span>
              <span class="info-value">{{ item.sort }}</span>
            </div>
          </div>
          
          <!-- 展开查看更多信息 -->
          <div v-if="expandedCards.includes(index)" class="mobile-card-detail">
            <div class="info-item">
              <span class="info-label">创建时间：</span>
              <span class="info-value">{{ parseTime(item.create_datetime) }}</span>
            </div>
            <div v-if="item.remark" class="info-item">
              <span class="info-label">备注：</span>
              <span class="info-value">{{ item.remark }}</span>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="mobile-card-actions">
            <el-button type="text" @click="toggleExpand(index)">
              {{ expandedCards.includes(index) ? '收起' : '查看详情' }}
            </el-button>
            <div>
              <el-button type="text" @click="handleUpdate(item)" :style="{ color: theme }"
                v-hasPermi="['permission:post:{id}:put']">
                <i class="el-icon-edit"></i> 修改
              </el-button>
              <el-button type="text" @click="handleDelete(item)" style="color: #F56C6C"
                v-hasPermi="['permission:post:{id}:delete']">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 移动端分页 -->
      <div class="mobile-pagination" v-if="total > 0">
        <div class="mobile-pagination-wrapper">
          <!-- 第一行：总数和每页条数 -->
          <div class="pagination-row top-row">
            <span class="el-pagination__total">共 {{ total }} 条</span>
            <el-select 
              v-model="queryParams.page_size" 
              size="mini" 
              class="el-pagination__sizes"
              @change="handleSizeChange">
              <el-option
                v-for="item in [10, 20, 30, 50]"
                :key="item"
                :label="`${item}条/页`"
                :value="item">
              </el-option>
            </el-select>
          </div>
          
          <!-- 第二行：页码导航 -->
          <div class="pagination-row bottom-row">
            <el-pagination
              background
              @current-change="handleCurrentChange"
              :current-page="queryParams.page"
              :page-size="queryParams.page_size"
              layout="prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加或修改岗位对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item
          label="岗位名称"
          prop="name"
        >
          <el-input
            v-model="form.name"
            placeholder="请输入岗位名称"
          />
        </el-form-item>
        <el-form-item
          label="岗位编码"
          prop="code"
        >
          <el-input
            v-model="form.code"
            placeholder="请输入编码名称"
          />
        </el-form-item>
        <el-form-item
          label="岗位顺序"
          prop="sort"
        >
          <el-input-number
            v-model="form.sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item
          label="岗位状态"
          prop="status"
        >
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark"
        >
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPost,
  getPost,
  delPost,
  addPost,
  updatePost,
  exportPost,
} from "@/api/vadmin/permission/post";

export default {
  name: "Post",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [
        { dictLabel: "正常", dictValue: 1 },
        { dictLabel: "停用", dictValue: 0 },
      ],
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        code: undefined,
        name: undefined,
        status: 1,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" },
        ],
        code: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" },
        ],
      },
      // 移动端相关
      expandedCards: [],
      screenWidth: document.body.clientWidth,
      mediaQueryList: null,
      isMobile: false
    };
  },
  computed: {
    // 主题颜色
    theme() {
      return this.$store.state.settings.theme;
    }
  },
  created() {
    this.getList();
    // this.getDicts("sys_normal_disable").then((response) => {
    //   this.statusOptions = response.data;
    // });
    
    // 初始化移动设备状态
    this.isMobile = document.body.clientWidth < 768;
    // 监听屏幕宽度变化
    this.mediaQueryList = window.matchMedia("(max-width: 768px)");
    this.mediaQueryList.addListener(this.handleScreenWidthChange);
  },
  beforeDestroy() {
    // 移除监听器
    if (this.mediaQueryList) {
      this.mediaQueryList.removeListener(this.handleScreenWidthChange);
    }
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listPost(this.queryParams).then((response) => {
        this.postList = response.results;
        this.total = response.count;
        this.loading = false;
      });
    },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      if (row.status == 1) {
        return "正常";
      } else {
        return "停用";
      }
      // return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        code: undefined,
        name: undefined,
        sort: 0,
        status: 1,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加岗位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      // console.log(2244422222, id);
      getPost(id).then((response) => {
        this.form = response;
        this.open = true;
        this.title = "修改岗位";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updatePost(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPost(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.id || this.ids;
      this.$confirm(
        '是否确认删除岗位编号为"' + postIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delPost(postIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有岗位数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportPost(queryParams);
        })
        .then((response) => {
          this.download(response.data.file_url, response.data.name);
        });
    },
    // 处理屏幕宽度变化
    handleScreenWidthChange(e) {
      this.screenWidth = document.body.clientWidth;
      this.isMobile = this.screenWidth < 768;
    },
    // 切换卡片展开状态
    toggleExpand(index) {
      const position = this.expandedCards.indexOf(index);
      if (position !== -1) {
        this.expandedCards.splice(position, 1);
      } else {
        this.expandedCards.push(index);
      }
    },
    // 处理分页大小变化
    handleSizeChange(val) {
      this.queryParams.page_size = val;
      this.getList();
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    }
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: transparent;
  padding: 0;
}

.mobile-container {
  padding: 10px;
}

.mobile-form {
  display: flex;
  flex-direction: column;
  
  .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }
}

.mobile-action-buttons {
  margin: 15px 0;
}

.mobile-card {
  margin-bottom: 15px;
  border-radius: 8px;
  
  .mobile-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    
    .card-title {
      .name {
        font-weight: bold;
        font-size: 16px;
      }
      
      .code {
        font-size: 14px;
        color: #909399;
        margin-left: 5px;
      }
    }
    
    .status-tag {
      font-size: 12px;
      padding: 2px 8px;
      border-radius: 4px;
      
      &.active {
        background-color: #f0f9eb;
        color: #67c23a;
      }
      
      &.inactive {
        background-color: #f4f4f5;
        color: #909399;
      }
    }
  }
  
  .mobile-card-info, .mobile-card-detail {
    .info-item {
      margin: 8px 0;
      font-size: 14px;
      display: flex;
      
      .info-label {
        color: #606266;
        margin-right: 5px;
        font-weight: bold;
      }
      
      .info-value {
        color: #303133;
      }
    }
  }
  
  .mobile-card-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 15px;
    border-top: 1px solid #ebeef5;
    padding-top: 10px;
  }
}

.mobile-pagination {
  margin-top: 20px;
  
  .mobile-pagination-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .pagination-row {
      width: 100%;
      display: flex;
      justify-content: center;
      margin-bottom: 10px;
      
      &.top-row {
        justify-content: space-between;
        align-items: center;
        
        .el-pagination__sizes {
          width: 110px;
        }
      }
    }
  }
}

.mobile-dialog {
  .el-dialog__body {
    padding: 10px 20px;
  }
  
  .el-form-item {
    margin-bottom: 15px;
  }
}
</style>
